<template>
  <el-dialog
    :visible="addShowDialog"
    v-bind="$attrs"
    v-on="$listeners"
    @close="close"
    :title="articleForm.id ? '修改文章' : '新增文章'"
  >
    <el-form
      ref="articleRef"
      :model="articleForm"
      :rules="rules"
      size="medium"
      label-width="120px"
      style="margin-left: -38px"
    >
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="articleForm.title"
          placeholder="请输入文章标题"
          clearable
          :style="{ width: '100%' }"
        >
        </el-input>
      </el-form-item>
      <el-form-item id="quillEditor" label="文章内容" prop="articleBody">
        <!--富文本编辑器组件-->
        <quill-editor
          v-model="articleForm.articleBody"
          ref="quillEditQuestion"
          :options="editorOption"
          style="height: 300px"
        ></quill-editor>
      </el-form-item>
        <!-- 图片上传组件辅助，组件内添加v-show=“false”属性，把该组件隐藏起来。-->
        <el-upload action="#" id="uploaderQuestion" v-show="false" :http-request="uploadQuestion" :before-upload="beforeAvatarUpload">
        </el-upload>
      <el-form-item label="视频地址" prop="videoURL">
        <el-input
          v-model="articleForm.videoURL"
          placeholder="请输入视频地址"
          clearable
          :style="{ width: '100%' }"
        >
        </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="handelConfirm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { add, update } from '@/api/hmmm/articles.js'
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  ['blockquote'], // 引用['blockquote']
  ['code-block', 'image', 'link'] // 代码块、图片、链接-----['code-block', 'image', 'link']
]
// 引入腾讯云COS，并创建实例
const COS = require('cos-js-sdk-v5')
const cos = new COS({
  SecretId: 'AKIDSjlW0D9xZuxkJcdOs50f3AzXooXzA5j6', // 身份识别ID
  SecretKey: '8zZrsc5HCrEK9hz0kDPKzNVLuCDxPbWA' // 身份秘钥
})
export default {
  inheritAttrs: false,
  components: { quillEditor },
  props: {
    addShowDialog: {
      type: Boolean,
      require: true
    },
    articleForm: {
      type: Object,
      require: true
    },
    currentPage: {
      type: [Number, String, Object],
      require: true
    }
  },
  data () {
    return {
      rules: {
        title: [{
          required: true,
          message: '请输入文章标题',
          trigger: 'blur'
        }],
        articleBody: [{
          required: true,
          message: '请输入文章内容',
          trigger: 'blur'
        }],
        videoURL: []
      },
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function (value) {
                if (value) {
                  document.querySelector('#uploaderQuestion .el-upload').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      }
    }
  },
  methods: {
    close () {
      this.$emit('update:articleForm', { title: undefined, articleBody: undefined, videoURL: undefined, id: undefined })
      this.$emit('update:addShowDialog', false)
    },
    handelConfirm () {
      this.$refs.articleRef.validate(async valid => {
        if (!valid) return
        // 有id，是修改
        if (this.articleForm.id) {
          try {
            await update(this.articleForm)
            this.$message.success('修改文章成功')
            this.$emit('updateArticleList')
          } catch (e) {
            this.$message.error('修改文章失败')
          }
        } else {
          // 没id，是新增
          try {
            await add(this.articleForm)
            this.$message.success('新增文章成功')
            this.currentPage = 1
            this.$emit('updateArticleList')
          } catch (e) {
            this.$message.error('新增文章失败')
          }
        }
        this.close()
      })
    },
    uploadAnswer (res) {
      this.upload(res, 'quillEditorAnswer')
    },
    uploadQuestion (res) {
      if (res.file) {
        this.isUploading = true
        cos.putObject(
          {
            Bucket: 'psrj07373039-1312444976' /* 必须 */,
            Region: 'ap-beijing' /* 存储桶所在地域，必须字段 */,
            Key: res.file.name,
            StorageClass: 'STANDARD',
            Body: res.file,
            onProgress: (progressData) => {
              console.log(JSON.stringify(progressData))
              this.percentage = progressData.percent * 100
            }
          }, (err, data) => {
            console.log(data, err)
            if (data.statusCode === 200) {
              const quill = this.$refs.quillEditQuestion.quill
              const length = quill.getSelection().index
              quill.insertEmbed(length, 'image', `https:${data.Location}`)
              quill.setSelection(length + 1)
            } else {
              this.$message.error('图片上传失败')
            }
          }
        )
      }
    },
    // 文件上传前处理函数
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style scoped lang='less'>
#quillEditor {
  margin-bottom: 75px !important;
}
</style>
